import { Node, mergeAttributes } from '@tiptap/core'

export default Node.create({
  name: 'video',

  group: 'block',

  atom: true,

  addAttributes() {
    return {
      src: {
        default: null
      },
      width: {
        default: 560
      },
      height: {
        default: 315
      },
      frameborder: {
        default: 0
      },
      allowfullscreen: {
        default: true
      }
    }
  },

  parseHTML() {
    return [
      {
        tag: 'iframe[src*="youtube.com"]'
      },
      {
        tag: 'iframe[src*="youtu.be"]'
      }
    ]
  },

  renderHTML({ HTMLAttributes }) {
    return ['iframe', mergeAttributes(HTMLAttributes, {
      frameborder: 0,
      allowfullscreen: true
    })]
  },

  addNodeView() {
    return ({ node }) => {
      const iframe = document.createElement('iframe')
      iframe.src = node.attrs.src
      iframe.width = node.attrs.width
      iframe.height = node.attrs.height
      iframe.frameBorder = node.attrs.frameborder
      iframe.allowFullscreen = node.attrs.allowfullscreen
      iframe.style.border = 'none'
      iframe.style.borderRadius = '8px'
      iframe.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)'

      const wrapper = document.createElement('div')
      wrapper.style.textAlign = 'center'
      wrapper.style.margin = '16px 0'
      wrapper.appendChild(iframe)

      return {
        dom: wrapper
      }
    }
  },

  addCommands() {
    return {
      setVideo: options => ({ commands }) => {
        return commands.insertContent({
          type: this.name,
          attrs: options
        })
      }
    }
  }
})
